#include "VisualDocumentAdaptor.h"

#include "QFile"
#include "QSaveFile"
#include "QTextStream"

VisualDocumentAdaptor::VisualDocumentAdaptor(shell::Access_interface &shell_access,
                                             std::shared_ptr<QtNodes::NodeDelegateModelRegistry> registry)
    : _shell_access(shell_access)
    , _model(registry)
{
}

QString VisualDocumentAdaptor::loadFile(const QString & fileName)
{
    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly))
        return file.errorString();

    QByteArray const wholeFile = file.readAll();

    _model.load(QJsonDocument::fromJson(wholeFile).object());
    setModified(false);
    return "";
}

QString VisualDocumentAdaptor::saveFile(const QString &fileName)
{
    _save_flag = true;

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly))
        return file.errorString();

    file.write(QJsonDocument(_model.save()).toJson());
    setModified(false);
    return "";
}

bool VisualDocumentAdaptor::wasSaved()
{
    if (_save_flag) {
        _save_flag = false;
        return true;
    }

    return false;
}

QString VisualDocumentAdaptor::text()
{
    return QJsonDocument(_model.save()).toJson();
}

bool VisualDocumentAdaptor::setText(const QString &text)
{
    _model.load(QJsonDocument::fromJson(QByteArray::fromStdString(text.toStdString())).object());
    setModified(false);
    return true;
}

bool VisualDocumentAdaptor::isModified()
{
    return _is_modified;
}

void VisualDocumentAdaptor::setModified(bool modified)
{
    _is_modified = modified;
    _shell_access.setCurrentDocumentWindowModified(modified);
}
